#!/usr/bin/env node
import puppeteer, { KnownDevices } from 'puppeteer';
import { promptQuestions } from './utils/promptUtils.mjs';
import { getPerformanceMetrics } from './utils/performanceUtils.mjs';
import { getFailedResources } from './utils/resourceUtils.mjs';
import { printReport } from './utils/reportUtils.mjs';
import path from 'path';
import fs from 'fs';

/**
 * 主程序入口函数
 * 负责协调整个性能测试流程：
 * 1. 获取用户输入
 * 2. 启动浏览器并配置
 * 3. 执行页面测试
 * 4. 收集性能数据
 * 5. 输出报告
 */
function getMainDomain(url) {
  const hostname = new URL(url).hostname;
  const parts = hostname.split('.');

  // 如果是 IP 地址，直接返回
  if (/^(\d{1,3}\.){3}\d{1,3}$/.test(hostname)) {
    return hostname;
  }

  let mainDomain;
  // 处理特殊的顶级域名，如 .com.cn, .net.cn 等
  if (
    parts.length >= 3 &&
    (parts.slice(-2).join('.') === 'com.cn' ||
      parts.slice(-2).join('.') === 'net.cn' ||
      parts.slice(-2).join('.') === 'org.cn' ||
      parts.slice(-2).join('.') === 'gov.cn')
  ) {
    // 返回最后三部分
    mainDomain = parts.slice(-3).join('.');
  } else {
    // 其他情况返回最后两部分
    mainDomain = parts.slice(-2).join('.');
  }

  // 在主域名前添加点号
  return '.' + mainDomain;
}

async function testDevice({ browser, deviceName, answers }) {
  console.log(`\n开始测试设备: ${deviceName ? deviceName : 'PC'}`);
  const page = await browser.newPage();

  // 设置 cookie（如果有）
  if (answers.hasCookie) {
    const mainDomain = getMainDomain(answers.url);
    const cookies = answers.cookieString.split(';').map(cookie => {
      const [name, value] = cookie.trim().split('=');
      return {
        name,
        value,
        domain: mainDomain,
        path: '/',
      };
    });
    await page.setCookie(...cookies);
  }

  // 判断是否为PC设备
  if (deviceName) {
    // 模拟设备
    await page.emulate(KnownDevices[deviceName]);
  }
  await page.setCacheEnabled(false);

  // 监听资源加载
  const { failedRequests, slowRequests } = await getFailedResources(page);

  console.log(`正在加载页面 (${deviceName ? deviceName : 'PC'})...`);
  await page.goto(answers.url, {
    waitUntil: ['networkidle0', 'domcontentloaded', 'load'],
  });

  // 等待页面完全加载
  await page.evaluate(() => {
    return new Promise(resolve => {
      if (document.readyState === 'complete') {
        resolve();
      } else {
        window.addEventListener('load', () => resolve());
      }
    });
  });

  // 收集性能指标
  const metrics = await getPerformanceMetrics(page);

  // 为每个设备创建单独的截图
  const hostname = new URL(answers.url).hostname;
  const testReportDir = path.join(process.cwd(), 'testReport');
  const deviceFileName = deviceName
    ? deviceName.toLowerCase().replace(/\s+/g, '_')
    : 'pc';
  const imgName = `${hostname}_${deviceFileName}_screenshot.png`;
  const imgReportPath = path.join(testReportDir, imgName);

  await fs.promises.mkdir(testReportDir, { recursive: true });
  await page.screenshot({ path: imgReportPath });

  // 输出该设备的测试报告
  console.log(`\n${deviceName ? deviceName : 'PC'} 测试结果:`);
  printReport({
    metrics,
    failedRequests,
    slowRequests,
    testReportDir,
    imgName,
    deviceName: deviceName || 'PC',
  });

  await page.close();
}

async function run() {
  try {
    const answers = await promptQuestions();
    const browser = await puppeteer.launch({
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    // 如果是移动端测试，为每个选中的设备创建新页面并测试
    if (answers.isMobile && answers.selectedDevices.length > 0) {
      for (const deviceName of answers.selectedDevices) {
        await testDevice({
          browser,
          deviceName,
          answers,
        });
      }
    } else {
      await testDevice({ browser, answers });
    }

    await browser.close();
  } catch (error) {
    // console.error('发生错误:', error);
    process.exit(1);
  }
}

run();
